/****************************************************************************

    Copyright 2008, 2009  Clark Scheff
    
    This file is part of G1 Psycho.

    G1 Psycho is free software: you can redistribute it and/or
    modify it under the terms of the GNU General Public License as published
    by the Free Software Foundation version 3 of the License.

    G1 Psycho is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with G1 Psycho. If not, see http://www.gnu.org/licenses
    
****************************************************************************/

package com.android.app.psycho;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.*;
import android.hardware.SensorManager;
import android.widget.SeekBar;
import android.widget.Toast;

public class Psycho extends Activity {
	public static final String PREFS_NAME = "PsychoPrefsFile";

	private SensorManager mSensorManager = null;
	private AudioManager mAudioManager = null;
	private GraphView mGraphView;
	private Menu mMenu;
	private boolean mResumed = false;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE); 
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mGraphView = new GraphView(this, mSensorManager);
        setContentView(mGraphView);
    }

    @Override
    protected void onStart() {
    	super.onStart();
    	// Restore preferences
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        boolean blood = settings.getBoolean("enableBlood", false);
        boolean lefty = settings.getBoolean("enableLefty", false);
        boolean strings = settings.getBoolean("loopStrings", false);
        float sense = settings.getFloat("sensitivity", 5.0f);
        mGraphView.setShowBlood(blood);
        mGraphView.setLefty(lefty);
        mGraphView.setLoopStrings(strings);
        mGraphView.setSenseOffset(sense);
    	mGraphView.invalidate();
    }
    
    @Override
    protected void onPause() {
    	mGraphView.pause();
    	super.onPause();
    }

    @Override
    protected void onResume() {
    	super.onResume();
    	if(true == mResumed)
    		mGraphView.resume();
    	mResumed = true;
    }
    
    @Override
    protected void onStop() {
    	super.onStop();
    	SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    	SharedPreferences.Editor editor = settings.edit();
    	editor.putBoolean("enableBlood", mGraphView.getShowBlood());
    	editor.putBoolean("enableLefty", mGraphView.getLefty());
    	editor.putBoolean("loopStrings", mGraphView.getLoopStrings());
    	editor.putFloat("sensitivity", mGraphView.getSenseOffset());
    	// Don't forget to commit your edits!!!
    	editor.commit();
//    	mGraphView.onStop();
    }
    
    @Override
	public void onConfigurationChanged(Configuration newConfig) {
    	super.onConfigurationChanged(newConfig);
    }

    // Called only the first time the options menu is displayed.
	// Create the menu entries.
	// Menu adds items in the order shown.
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		mMenu = menu;
		if(mGraphView.getShowBlood() == true) {
				menu.add(0, 0, 0, R.string.menu_clear_blood);
				menu.add(0, 1, 0, R.string.menu_disable_blood);
		}
		else
			menu.add(0, 1, 0, R.string.menu_enable_blood);
		menu.add(1, 2, 2, R.string.menu_reset_music);
		if(mGraphView.getLefty())
			menu.add(1, 3, 2, R.string.menu_righty_mode);
		else
			menu.add(1, 3, 2, R.string.menu_lefty_mode);
		
		if(mGraphView.getLoopStrings())
			menu.add(2, 4, 3, R.string.menu_include_bass);
		else
			menu.add(2, 4, 3, R.string.menu_loop_strings);
		mMenu.add(3, 5, 4, "Sensitivity");
		return true;
	}

 	// Activity callback that lets your handle the selection in the class.
	// Return true to indicate that you've got it, false to indicate
	// that it should be handled by a declared handler object for that
	// item (handler objects are discouraged for reasons of efficiency).
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()) {
		case 0:
			mGraphView.clearBlood();
			return true;
		case 1:
			boolean show = mGraphView.getShowBlood();
			if(true == show) { 
				mMenu.removeItem(0);
				mMenu.removeItem(1);
				mMenu.add(0, 1, 0, R.string.menu_enable_blood);
				Toast.makeText(this, R.string.note_blood_disabled, Toast.LENGTH_SHORT).show();
			}
			else {
				mMenu.add(0, 0, 0, "Clear Blood");
				mMenu.removeItem(1);
				mMenu.add(0, 1, 0, R.string.menu_disable_blood);
				Toast.makeText(this, R.string.note_blood_enabled, Toast.LENGTH_SHORT).show();
			}
			
			mGraphView.setShowBlood(!show);
			if(false == !show)
				mGraphView.clearBlood();
			return true;
		case 2:
			mGraphView.resetMusic();
			Toast.makeText(this, R.string.note_music_reset, Toast.LENGTH_SHORT).show();
			return true;
		case 3:
			boolean lefty = mGraphView.getLefty();
			mMenu.removeItem(3);
			if(lefty) {
				mMenu.add(1, 3, 2, R.string.menu_lefty_mode);
				Toast.makeText(this, R.string.note_righty, Toast.LENGTH_SHORT).show();
			}
			else {
				mMenu.add(1, 3, 2, R.string.menu_righty_mode);
				Toast.makeText(this, R.string.note_lefty, Toast.LENGTH_SHORT).show();
			}
			mGraphView.setLefty(!lefty);
			return true;
		case 4:
			boolean strings = mGraphView.getLoopStrings();
			mMenu.removeItem(4);
			if(strings) {
				mMenu.add(2, 4, 3, R.string.menu_loop_strings);
				Toast.makeText(this, R.string.note_include_bass, Toast.LENGTH_SHORT).show();
			} else {
				mMenu.add(2, 4, 3, R.string.menu_include_bass);
				Toast.makeText(this, R.string.note_loop_strings, Toast.LENGTH_SHORT).show();
			}
			mGraphView.setLoopStrings(!strings);
			return true;
		case 5:
            LayoutInflater factory = LayoutInflater.from(this);
            final View dv = factory.inflate(R.layout.sensedialog, null);
            float sensitivity = 15.0f - mGraphView.getSenseOffset();
            new AlertDialog.Builder(Psycho.this)
                .setTitle("Adjust Sensitivity")
                .setIcon(R.drawable.icon)
                .setView(dv)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
    
                        /* User clicked OK so do some stuff */
                    	SeekBar sb = (SeekBar) dv.findViewById(R.id.sensitivity);
                    	float sense = 15 - sb.getProgress();
                    	mGraphView.setSenseOffset(sense);
//                    	Toast.makeText(TheSchwartz.this, "Sensitivty set to "+(int)sense, Toast.LENGTH_SHORT);
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        /* User clicked cancel so do some stuff */
                    }
                })
                .create()
                .show();
            SeekBar sb = (SeekBar) dv.findViewById(R.id.sensitivity);
            sb.setProgress((int)sensitivity);
            sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

				@Override
				public void onProgressChanged(SeekBar seekBar, int progress,
						boolean fromTouch) {
					// TODO Auto-generated method stub
                	float sense = 10 - seekBar.getProgress();
                	mGraphView.setSenseOffset(sense);
					
				}

				@Override
				public void onStartTrackingTouch(SeekBar seekBar) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onStopTrackingTouch(SeekBar seekBar) {
					// TODO Auto-generated method stub
					
				}
            	
            });
            return true;
		}
		return false;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		super.onKeyDown(keyCode, event);
		if(event.getAction() == KeyEvent.ACTION_DOWN) {
			switch(event.getKeyCode()) {
			case KeyEvent.KEYCODE_VOLUME_UP:
		        mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, 
		        		AudioManager.ADJUST_RAISE, 
		        		AudioManager.FLAG_SHOW_UI);
				return true;
			case KeyEvent.KEYCODE_VOLUME_DOWN:
		        mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, 
		        		AudioManager.ADJUST_LOWER, 
		        		AudioManager.FLAG_SHOW_UI);
				return true;
			}
		}
		return false;
	}
}